package cn.mygweb.admin.modules.tools.controller;

import java.util.Hashtable;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.Result;
import com.google.zxing.common.BitMatrix;

import cn.mygweb.common.controller.BaseController;
import cn.mygweb.common.pojo.JsonResult;
import cn.mygweb.common.utils.QrcodeUtil;
import cn.mygweb.common.utils.UploadUtils;

/** 
* <p>Title: QrcodeController.java</p>
* <p>Description: 二维码生成器</p>  
* @author gxb 
* @date 2019年7月23日 
* <p>Copyright: Copyright (c) 2019</p>
* <p>Company: www.mygweb.cn</p> 
*/
@RequestMapping("/admin/tools/qrcode")
@Controller
public class QrcodeController extends BaseController{

	/**
	 * <p>Title: qrcode</p>
	 * <p>Description: 访问二维码生成器页面</p>
	 * @return
	 */
	@RequestMapping("")
	public String qrcode() {
		return "admin/modules/tools/qrcode.html";
	}
	
	/**
	 * <p>Title: textToQrcode</p>
	 * <p>Description: 将文本生成二维码</p>
	 * @param content
	 * @return
	 */
	@RequestMapping("/textToQrcode")
	@ResponseBody
	public JsonResult textToQrcode(String content) {
		try {
			Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
			hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
			BitMatrix matrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, 200, 200, hints);
			String path = UploadUtils.uploadQrcode(matrix, uploadFilePath);
			return JsonResult.ok(path);
		} catch (Exception e) {
			e.printStackTrace();
			return JsonResult.errorMsg("二维码制作失败");
		}
	}
	
	@RequestMapping("/decode")
	@ResponseBody
	public JsonResult decode(@RequestParam("file") MultipartFile file) {
		String path = UploadUtils.uploadReturnRealPath(file, uploadFilePath, UploadUtils.QRCODE);
		Result result = QrcodeUtil.decodeQrcode(path);
		return JsonResult.ok(result.getText());
	}
}
